package com.huawei.ju;

/**
 * @description https://nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024?tpId=295&tqId=663&ru=%2Fpractice%2Fc087914fae584da886a0091e877f2c79&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj
 *  给出一个升序排序的链表，删除链表中的所有重复出现的元素，只保留原链表中只出现一次的元素。
 * @author wj
 * @date 2023-10-04
 */
public class BM16 {

  public static void main(String[] args) {
    BM16 bm16 = new BM16();
    ListNode listNode1 = new ListNode(1);
    ListNode listNode2 = new ListNode(1);
//    ListNode listNode3 = new ListNode(1);
    ListNode listNode3 = new ListNode(2);
    ListNode listNode4 = new ListNode(3);
    ListNode listNode5 = new ListNode(3);
    ListNode listNode6 = new ListNode(4);
    listNode5.next = listNode6;
    listNode4.next = listNode5;
    listNode3.next = listNode4;
    listNode2.next = listNode3;
    listNode1.next = listNode2;
    ListNode listNode = bm16.deleteDuplicates(listNode1);
    System.out.println(listNode);
  }

  /**
   * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
   *
   *
   * @param head ListNode类
   * @return ListNode类
   */
  public ListNode deleteDuplicates (ListNode head) {
    if (head == null || head.next == null) {
      return head;
    }
    // 1,1,1,2,3,3,4 -> 2, 4
    ListNode temp1 = new ListNode(-1);
    temp1.next = head;
    ListNode temp2 = temp1;
    while (temp2.next != null) {
      if (temp2.next.next != null && temp2.next.val == temp2.next.next.val) {
        ListNode temp = temp2.next.next;
        int val = temp.val;
        while (temp != null && temp.val == val) {
          temp = temp.next;
        }
        temp2.next = temp;
      } else {
        temp2 = temp2.next;
      }
    }
    return temp1.next;
  }

  public static class ListNode {
    int val;
    ListNode next = null;
    public ListNode(int val) {
      this.val = val;
    }
  }
}
